#include "ConnMySqHelper.h"

#include <QDebug>
#include <QString>
#include <QSqlDatabase>


void ConnMySqHelper::initDbPool(const ConnInfo_Db& dbInfo)
{
    ConnectionPool::initInfo(dbInfo);
}

ConnMySqHelper::ConnMySqHelper()
{ 
        //
}

ConnMySqHelper::~ConnMySqHelper()
{
    //
}

QSharedPointer<ConnMySqHelper> ConnMySqHelper::GetThreadMySqlHelp()
{
    static QSharedPointer<ConnMySqHelper> instance = QSharedPointer<ConnMySqHelper>::create();
    return instance;
}

bool ConnMySqHelper::select(const QString& cmd, QVector<QSqlRecord>& last_query_result)
{
    bool result = false;

    QString name;

    {
        QSqlDatabase db_base = ConnectionPool::openConnection();
        name = db_base.connectionName();
        try
        {
            last_query_result.clear();
            QSqlQuery query = QSqlQuery(db_base);
            if (query.exec(cmd))
            {
                while (query.next())
                {
                    last_query_result.push_back(query.record());
                }
                result = true;
            }
            else
            {
                qDebug()<< "sql error:" << cmd;
                result = false;
            }


        }
        catch (...)
        {
            qDebug() << "error!!!  " << cmd;
            result = false;
        }

        db_base.close();
    }
        
    QSqlDatabase::removeDatabase(name);

    return result;
}

bool ConnMySqHelper::execSqlCmd(const QString& op)
{
    bool result = false;
    QString name;

    {
        QSqlDatabase db_base = ConnectionPool::openConnection();
        name = db_base.connectionName();

        try
        {
            QSqlQuery query = QSqlQuery(db_base);

            if (query.exec(op))
            {
                result = true;
            }
            else
            {
                result = false;
            }
        }
        catch (...)
        {
            result = false;
        }

        db_base.close();
    }

    QSqlDatabase::removeDatabase(name);

    return result;
}

bool ConnMySqHelper::testLocalDbConn()
{
    bool nRes = false;
    QString  testOnBorrowSql = "SELECT 1";
    if (execSqlCmd(testOnBorrowSql))
    {
        nRes = true;
    }
    else {
        nRes = false;
    }

    return nRes;
}

bool ConnMySqHelper::local_createSiteDataBase(QString& tablename, QString& constructSentence)
{

    QString sqlCmd = constructSentence.arg(tablename);

    try
    {
        bool nRes = false;
        if (tablename.isEmpty() || constructSentence.isEmpty()
            || constructSentence.lastIndexOf("CREATE TABLE") < 0)
            return false;
        
        nRes = execSqlCmd(sqlCmd);
        return nRes;
    }
    catch (...)
    {
        qDebug() << "error!!!! "  << sqlCmd;
        return false;
    }
}
